<?php

namespace Apps\Backend\Controllers;
use Apps\Backend\Forms\LoginForm;
use Apps\Backend\Models\SuccessLogins;
use Apps\Backend\Models\Users;
class LoginController extends \Phalcon\Mvc\Controller
{
    public function initialize(){
        $this->tag->setTitle("VEGALIFE");
        $this->tag->setDefaults(array('keywords'=>'vegalife',
            'description'=>'vegalife',
        ));
    }

    public function indexAction(){
        $session = $this->session->get('auth-identity');
        if(count($session) >2){
            return $this->response->redirect(PUBLIC_URL.'backend/admin-articlegame/index');
        }
        $form  = new LoginForm();
        $error = '';
        if ($this->request->isPost()) {
            $data = $this->request->getPost();
            if ($form->isValid($data)) {
                $result = $this->auth->check($data);
                if($result['error'] =='false')
                    return $this->response->redirect(PUBLIC_URL.'backend/admin-articlegame/index');
                else
                    $error = $result['message'];
            }
        }
        $this->view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_ACTION_VIEW);//Ưu tien view action
        $this->view->setVar('error',$error);
        $this->view->formLogin = $form;
    }
    public function logoutAction(){
        $session = $this->session->get('auth-identity');
        if(count($session) >0){
            $userAddress = $this->request->getClientAddress();
            $idUser      = $session['id'];
            $email       = $session['email'];
            $successLogin = SuccessLogins::findFirst(array("created_by = '{$idUser}' AND ip_address = '$userAddress'"));
            if($successLogin){
                $successLogin->save(array('status'=>'0'));    
            }
            $user = Users::findFirstById($idUser);
            //$user->save(array('visited_date'=>time(),'ip'=>$userAddress));
            $this->session->destroy();
        }
        return $this->response->redirect(PUBLIC_URL);
    }
    public function noAccessAction(){
        $response = new \Phalcon\Http\Response();
        $response->setStatusCode("500",'No Access');
        $this->view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_ACTION_VIEW);//Ưu tien view action
    }
    public function route404Action(){
        $response = new \Phalcon\Http\Response();
        $response->setStatusCode("404",'No Access');
        $this->view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_ACTION_VIEW);//Ưu tien view action
    }
}